package com.toutiao.model

import org.iq80.leveldb.Options
import org.iq80.leveldb.DB
import org.iq80.leveldb.DBIterator
import org.iq80.leveldb.CompressionType
import org.fusesource.leveldbjni.JniDBFactory.{factory => LevelFactory}

import java.io.File
import java.nio.ByteBuffer
import java.io.PrintWriter

import scala.collection.mutable.ArrayBuffer

import org.apache.log4j.Logger

class KvDB(location:String) {
 
  private val log = Logger.getLogger(this.getClass.getName)
  
  val op = new Options
  op.createIfMissing(true)
  op.cacheSize(64*1024*1024)
  op.writeBufferSize(32*1024*1024)
  op.blockSize(16*1024)
  op.maxOpenFiles(65536)
  op.compressionType(CompressionType.NONE)
  
  val db = LevelFactory.open(new File(location),op) 
  
  def asArrayByte(k:Long) = {
    ByteBuffer.allocate(8).putLong(k).array()
  }
  def asLong(k:Array[Byte]) = {
    ByteBuffer.wrap(k).getLong
  }
  
  def put(k:Long,v:String) = {
    val kk = asArrayByte(k)
    val vv = v.getBytes
    db.put(kk,vv)
  }
  
  def get(k:Long) = {
    val kk = asArrayByte(k)
    new String(db.get(kk))
  }
  
  def remove(k:Long) = {
    val kk = asArrayByte(k)
    db.delete(kk)
  }
  
  def getDB = {
    val xs = new ArrayBuffer[(Long,String)]
    val iterator = db.iterator
    try {
      iterator.seekToFirst
      while (iterator.hasNext) {
        val u = iterator.peekNext
        val k = asLong(u.getKey)
        val v = new String(u.getValue)
        xs.append((k,v))
        iterator.next
      }
      
    }
    finally {
      iterator.close
    }
    xs.toMap
  }

}
